﻿using System;
using System.Collections.Generic;
using System.IO;
using Docentric.Examples.Data.BusinessObjects;
using Docentric.Examples.Data.BusinessObjects.DataModel;
using Docentric.Word;


namespace Docentric.Examples.Browser
{
	public class ConditionalContentExample : ExampleBase
	{
		// Constructor
		public ConditionalContentExample()
		{
			Name = "ConditionalContent";
			Title = "Conditional Content";
			Description = "The example shows how it is possible to conditionally include or exclude certain parts of a document using the 'If' element. Here we want to display a customer info and the customer's company and address will only be rendered if the customer is from Boston. The 'If' element could be bound to a boolean data but instead we marked it as unbound. This means that its value must be provided in code manually by using the 'ElementInitialize' event.";
			HelpTopicPage = "Examples_ConditionalContent";
		}


		private Customer customer;

		// GenerateReport
		public override string GenerateReport()
		{
			// Get the customer object with the Id = 15.
			customer = DataAccess.GetCustomerById(15);

			// Create a temporary file for the generated report document.
			string reportDocumentFileName = System.IO.Path.GetTempPath() + "GeneratedReport_" + Guid.NewGuid().ToString() + ".docx";
			using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
			{
				// Open the report template file.
				using (Stream reportTemplateStream = GetReportTemplate())
				{
					// Generate the report document using 'DocumentGenerator'.
					DocumentGenerator dg = new DocumentGenerator(customer);
					dg.ElementInitialize += new ElementInitializeHandler(dg_ElementInitialize);		// Hook to the 'ElementInitialize' in order to be able to provide values for unbound elements.
					DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);
					if (result.HasErrors)
					{
						foreach (Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);
					}
				}
			}

			return reportDocumentFileName;
		}
		

		// Provide values for unbound elements.
		private void dg_ElementInitialize(object sender, ElementInitializeEventArgs e)
		{
			if (e.Element.Name == "IsFromBoston")
			{
				e.Element.AsIf().Value = customer.Address.City == "Boston";
			}

			if (e.Element.Name == "IsFromBoston_Disclaimer")
			{
				e.Element.AsIf().Value = customer.Address.City != "Boston";
			}
		}
	}
}
